from django_filters.rest_framework import FilterSet, CharFilter, BooleanFilter
from django.db.models import Q
from .models import Server
import json

class ServerFilter(FilterSet):
    """自定义Server过滤器，使用Python逻辑处理JSONField"""
    tag = CharFilter(method='filter_tag')
    tags = CharFilter(method='filter_tags')
    category = CharFilter(method='filter_category')
    language = CharFilter(method='filter_language')
    is_hot = BooleanFilter(method='filter_hot')
    access_mode = CharFilter(method='filter_access_mode')
    
    def filter_tag(self, queryset, name, value):
        """过滤包含特定标签的服务器"""
        if not value:
            return queryset
        
        # 获取所有服务器，然后在Python中过滤
        filtered_ids = []
        for server in queryset:
            try:
                tags = json.loads(server.tags) if isinstance(server.tags, str) else server.tags
                if tags and value in tags:
                    filtered_ids.append(server.id)
            except (json.JSONDecodeError, TypeError):
                continue
        
        return queryset.filter(id__in=filtered_ids)
    
    def filter_tags(self, queryset, name, value):
        """处理多个标签过滤"""
        if not value:
            return queryset
        
        tag_list = [tag.strip() for tag in value.split(',')]
        if not tag_list:
            return queryset
        
        # 获取所有服务器，然后在Python中过滤
        filtered_ids = []
        for server in queryset:
            try:
                server_tags = json.loads(server.tags) if isinstance(server.tags, str) else server.tags
                if server_tags and any(tag in server_tags for tag in tag_list):
                    filtered_ids.append(server.id)
            except (json.JSONDecodeError, TypeError):
                continue
        
        return queryset.filter(id__in=filtered_ids)
    
    def filter_category(self, queryset, name, value):
        """过滤包含特定分类的服务器"""
        if not value:
            return queryset
        
        category_list = [cat.strip() for cat in value.split(',')]
        if not category_list:
            return queryset
        
        # 获取所有服务器，然后在Python中过滤
        filtered_ids = []
        for server in queryset:
            try:
                categories = json.loads(server.category) if isinstance(server.category, str) else server.category
                if categories and any(cat in categories for cat in category_list):
                    filtered_ids.append(server.id)
            except (json.JSONDecodeError, TypeError):
                continue
        
        return queryset.filter(id__in=filtered_ids)
    
    def filter_hot(self, queryset, name, value):
        """过滤热门MCP Server"""
        if not value:
            return queryset
        
        # 获取所有服务器，然后在Python中过滤
        filtered_ids = []
        for server in queryset:
            try:
                tags = json.loads(server.tags) if isinstance(server.tags, str) else server.tags
                if tags and "热门" in tags:
                    filtered_ids.append(server.id)
            except (json.JSONDecodeError, TypeError):
                continue
        
        return queryset.filter(id__in=filtered_ids)
    
    def filter_access_mode(self, queryset, name, value):
        if not value:
            return queryset
        
        if value.lower() == 'huawei_online':
            return queryset.filter(access_mode != 'LOCAL', is_internal=True)
        # 处理多个access_mode
        access_mode_list = value.split(',')
        if len(access_mode_list) > 0:
            return queryset.filter(access_mode__in=access_mode_list)
        else:
            return queryset.filter(access_mode=value)
    
    class Meta:
        model = Server
        fields = {
            'is_internal': ['exact'],
            'is_official': ['exact'],
            'provider': ['exact'],
            'auth_method': ['exact'],
            'from_site': ['exact'],
            'dev_language': ['exact'],
        }
